package com.igeek.clud_system.controller;



import com.igeek.clud_system.dao.CommentDao;
import com.igeek.clud_system.dao.StudentDao;
import com.igeek.clud_system.entity.*;
import com.igeek.clud_system.service.ActivityService;
import com.igeek.clud_system.service.ClubService;
import com.igeek.clud_system.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class ActivityController {
    @Autowired
    ActivityService activityService;
    @Autowired
    ClubService clubService;
    @Autowired
    CommentDao commentDao;
    @Autowired
    StudentDao studentDao;
    //保存活动图片路径
    private static final String UPLOAD_DIR = "src/main/resources/static/activityImg/";

    /**
     * 查询所有活动
     */
    @GetMapping("activity")
    public List<Activity> findAllActivity(){
        // 查询所有活动
        List<Activity> list = activityService.findActivity();
        if(list !=null){
            return list;
        }
        else {
            return null;
        }
    }

    /**
     * 查询活动对应的社团
     * @param id
     * @return
     */
    @GetMapping("activity/{id}")
    public Club findClub(@PathVariable ("id") Integer id){
        Club club = activityService.findClub(id);
        return club;
    }

    /**
     * 查询活动详情，包括社团信息、社长信息和管理员信息
     * @param id
     * @return
     */
    @GetMapping("activityinfo/{id}")
    public Map<String, Object> findFullActivityInfo(@PathVariable("id") Integer id) {
        // 查询活动详情
        Activity activity = activityService.findActivityById(id);
        Club club = activityService.findClub(id);
        Student president = activityService.findPre(id);
        List<Student> admins = activityService.findAdmin(id);

        Map<String, Object> response = new HashMap<>();
        response.put("activity", activity);
        response.put("club", club);
        response.put("president", president);
        response.put("admins", admins);

        return response;
    }

    /**
     * 模糊查询活动
     * @param activityName
     * @param clubName
     * @return
     */
    @GetMapping("activity/search")
    public List<Activity> searchActivities(@RequestParam(required = false) String activityName, @RequestParam(required = false) String clubName) {
        return activityService.searchActivities(activityName, clubName);
    }


    /**
     * 发布活动
     * @param activityName 活动名称
     * @param activityImage 活动图片
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param activityLocation 活动地点
     * @param activityMaxNumber 活动人数上限
     * @param activityContent 活动内容
     */
    @PostMapping("activity/publish")
    public void publishActivity(
            @RequestParam("activityName") String activityName,
            @RequestParam("activityImage") MultipartFile activityImage,
            @RequestParam("startTime") String startTime,
            @RequestParam("endTime") String endTime,
            @RequestParam("activityLocation") String activityLocation,
            @RequestParam("activityMaxNumber") int activityMaxNumber,
            @RequestParam("activityContent") String activityContent
    ) {
        Activity activity = new Activity();
        activity.setActivityName(activityName);
        activity.setActivityLocation(activityLocation);
        activity.setMaxNumber(activityMaxNumber);
        activity.setActivityContent(activityContent);
        activity.setStartTime(DateUtil.datetoString(DateUtil.stringToDate(startTime)));
        activity.setEndTime(DateUtil.datetoString(DateUtil.stringToDate(endTime)));
        // 处理文件上传
        if (!activityImage.isEmpty()) {
            try {
                // 生成唯一的文件名
                String fileName = UUID.randomUUID().toString() + "_" + activityImage.getOriginalFilename();
                Path path = Paths.get(UPLOAD_DIR + fileName);
                Files.createDirectories(path.getParent());
                Files.copy(activityImage.getInputStream(), path);
                // 设置活动图片路径
                activity.setActivityHead(fileName);
            } catch (IOException e) {
                e.printStackTrace();
                // 处理文件上传异常
                throw new RuntimeException("文件上传失败", e);
            }
        }
        activityService.insertActivity(activity);
        // System.out.println(activity);
    }

    /**
     * 获取评论列表
     * @param activityId 活动ID
     * @return 评论列表
     */
    @GetMapping("activity/comments/{activityId}")
    public Map<String,Object> getComments(@PathVariable("activityId") Integer activityId) {
        List<Comment> comments = activityService.findComments(activityId);
        Map<String, Object> commentMap = new HashMap<>();
        List<Comment> commentList = new ArrayList<>();
        List<Student> studentList = new ArrayList<>();
        for (Comment comment : comments) {
            Student student = studentDao.findStudentById(comment.getStudentId());
            commentList.add(comment);
            studentList.add(student);
            commentMap.put("students", studentList);
            commentMap.put("comments", commentList);
        }
        return commentMap;
    }
    /**
     * 添加评论
     * @param activityId 活动ID
     * @param commentContent 评论内容
     * @param commentGrade 评论分数
     */
    @PostMapping("activity/comment")
    public void addComment(
            @RequestParam("activityId") Integer activityId,
            @RequestParam("commentContent") String commentContent,
            @RequestParam("commentGrade") Integer commentGrade
    ) {
        Comment comment = new Comment();
        comment.setActivityId(activityId);
        comment.setCommentContent(commentContent);
        comment.setCommentGrade(commentGrade);
        comment.setCommentTime(DateUtil.datetoString(new Date()));

        activityService.insertComment(comment);
    }

    /**
     *  根据社团ID查询活动
     * @param clubId
     * @return
     */
    @GetMapping("activity/club/{clubId}")
    public List<Activity> findActivitiesByClubId(@PathVariable("clubId") Integer clubId) {
        return activityService.findAllByClubId(clubId);
    }
    // 查询活动参与成员信息
    @GetMapping("activity/member/{activityId}")
    public List<Student> findActivityMembers(@PathVariable("activityId") Integer activityId) {
        List<Student> studentList = activityService.findActivityMembers(activityId);
        // System.out.println(studentList);
        return studentList;
    }

    // 更新成员的参与状态
    @PostMapping("activity/member/update")
    public void updateMemberStatus(
            @RequestParam("activityId") Integer activityId,
            @RequestParam("studentId") Integer studentId,
            @RequestParam("status") Integer status
    ) {
        activityService.updateMemberStatus(activityId, studentId, status);
    }

    /**
     *  根据社团ID和活动ID查询活动参与成员信息
     * @param clubId
     * @param activityId
     * @return
     */
    @GetMapping("activity/club/{clubId}/{activityId}")
    public List<Student> findByClubIdAndActivityId(@PathVariable("clubId") Integer clubId,@PathVariable("activityId") Integer activityId) {
        return activityService.findByClubIdAndActivityId(clubId, activityId);
    }

    /**
     * 插入活动参与表
     * @param activityId
     * @param studentId
     */
    @PostMapping("activity/attend/{activityId}/{studentId}")
    public void insertActivityAttend(@PathVariable("activityId") Integer activityId,@PathVariable("studentId") Integer studentId){
        activityService.insertActivityAttend(activityId,studentId);
        System.out.println("插入活动参与表成功");
    }
}
